#![recursion_limit = "256"]
mod constants;
mod handlers;

use std::path::PathBuf;
use tauri::{
    http,
    plugin::{Builder, TauriPlugin},
    AppHandle, Manager, Runtime,
};

/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
    //
    tauri::async_runtime::block_on(async move {
        //执行数据库脚本
        tracing::debug!("节点启动");
        let result = model_graph_peer::peer_start().await;

        result
    })
    .expect("节点启动失败！");

    Builder::new("mg-peer")
        .invoke_handler(tauri::generate_handler![
            handlers::peer_id,
            handlers::peer_login,
            handlers::peer_status,
            handlers::peer_assistant_chat,
            handlers::peer_assistant_sv2tts,
            handlers::peer_assistant_shell,
            handlers::peer_assistant_batch_script,
            handlers::channel_pubsub_publish,
            handlers::channel_pubsub_publish_message,
            handlers::channel_pubsub_subscribe,
            handlers::channel_uicmd_response,
            handlers::channel_uicmd_remote_request,
        ])
        .register_uri_scheme_protocol("rrapp", rrapp_protocol)
        .setup(|app, plugin| {
            app.manage(handlers::ContextState::default());
            // if let Some(main_window) = app.get_window("main") {
            //     tracing::debug!("xxxxxx");
            //     // 注册回调
            //     model_graph_channel::pubsub::set_on_message_callback(
            //         &String::from("*"),
            //         Box::new(move |message| {
            //             tracing::debug!("*消息:{:?}",message);
            //             main_window
            //                 .emit("pubsub", message)
            //                 .map_err(|err| anyhow::anyhow!("{}", err));
            //         }),
            //     );
            // }
            Ok(())
        })
        .build()
}

pub fn rrapp_protocol<R: Runtime>(
    _app_handle: &AppHandle<R>,
    request: http::Request<Vec<u8>>,
) -> http::Response<Vec<u8>> {
    let current_result = tauri::async_runtime::TokioHandle::try_current();

    let f = async move {
        // 请求
        model_graph_peer::tauri_http_request(request).await
    };

    let result = match current_result {
        Ok(current) => current.block_on(f),
        Err(_) => {
            let rt = tauri::async_runtime::TokioRuntime::new().unwrap();
            rt.handle().block_on(f)
        }
    };

    match result {
        Ok(r) => r,
        Err(err) => {
            tracing::error!("{}", err);
            let body: Vec<u8> = vec![];
            http::Response::builder().body(body).unwrap()
        }
    }
}
